<template>
  <el-drawer
    :show-close="false"
    :size="860"
    :wrapperClosable="false"
    :visible.sync="$attrs.visable"
    :before-close="handleClose"
  >
    <template slot="title">
      <div>
        <i class="el-icon-close f-16 mr-12 commhover" @click="handleClose"></i>
        <span class="f-16 c_text2">{{ title }}</span>
      </div>
    </template>
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="140px"
      class="h_full p-20 of_auto pb-60"
    >
      <div class="formcard">
        <el-form-item label="分组设置：" prop="group">
          <el-cascader
            class="w_full"
            v-model="form.group"
            size="small"
            :options="options"
            clearable
            :props="propsCascader"
            @change="handleChange"
            popper-class='cascadermenu '
          ></el-cascader>
        </el-form-item>
      </div>
      <div class="formcard">
        <el-form-item label="话术标题：" prop="title">
          <el-input
            v-model="form.title"
            size="small"
            maxlength="15"
            placeholder="标题用于后续查找，最多输入15个字"
          ></el-input>
        </el-form-item>
      </div>
      <div class="formcard">
        <el-form-item label="话术内容：" prop="messageList">
          <div v-if="form.messageList.length" class="bg_fff messbox">
            <div
              v-for="(item, index) in form.messageList"
              :key="index"
              class="flexbetween messageitem p-10"
            >
              <div class="flex aligncenter">
                <div class="numberindex ml-12 mr-12">{{ index + 1 }}</div>
                <!-- 文字 -->
                <div v-if="item.contentType == '文本'" class="m_textbox">
                  {{ item.contentJson }}
                </div>
                <div v-else-if="item.contentType == '图片'">
                  <img :src="item.contentJson" alt="" class="m_imgbox" />
                </div>
              </div>
              <div class="flex mr-8">
                <!-- add -->
                <div v-if='form.messageList.length>=100' class="m_btn flexcenter commhover mr-8 hovernot">
                  <i class="el-icon-plus"></i>
                </div>
                <el-dropdown v-else trigger="click">
                  <div class="m_btn flexcenter commhover mr-8">
                    <i class="el-icon-plus"></i>
                  </div>
                  <el-dropdown-menu slot="dropdown">
                    <div class="flex dropflex"> 
                      <div v-for="(item, i) in typeList" :key="i" class="mr-8">
                        <el-button
                          size="small"
                          class="btn_item"
                          @click="handleTypeOpen(item, index)"
                        >
                          {{ item.name }}
                          <input
                            v-if="item.id == 2 || item.id == 3 || item.id == 4"
                            type="file"
                            :id="'photo' + i"
                            class="filebtn"
                            :accept="item.accept"
                            @change="chooseUpload($event, item, i)"
                          />
                          <el-tooltip
                            class="item"
                            effect="dark"
                            popper-class="btntooltip"
                            :content="item.info"
                            placement="top-start"
                          >
                            <i v-if="item.info" class="el-icon-info"></i>
                          </el-tooltip>
                        </el-button>
                      </div>
                    </div>
                  </el-dropdown-menu>
                </el-dropdown>
                <div
                  class="m_btn flexcenter commhover mr-8"
                  @click="handleEdit(item, index)"
                >
                  <i class="el-icon-edit"></i>
                </div>
                <div
                  class="m_btn flexcenter commhover mr-8"
                  @click="handleDelete(item, index)"
                >
                  <i class="el-icon-delete"></i>
                </div>
                <div class="m_line commhover"></div>
                <div
                  v-if="index !== form.messageList.length - 1"
                  class="m_btn flexcenter commhover mr-8"
                  @click="handleDown(index)"
                >
                  <i class="el-icon-download"></i>
                </div>
                <div
                  v-if="index !== form.messageList.length - 1"
                  class="m_btn flexcenter commhover mr-8"
                  @click="handleMoveDown(index)"
                >
                  <i class="el-icon-arrow-down"></i>
                </div>
                <div
                  v-if="index !== 0"
                  class="m_btn flexcenter commhover mr-8"
                  @click="handleMoveTop(index)"
                >
                  <i class="el-icon-arrow-up"></i>
                </div>
                <div
                  v-if="index !== 0"
                  class="m_btn flexcenter commhover"
                  @click="handleTop(index)"
                >
                  <i class="el-icon-upload2"></i>
                </div>
              </div>
            </div>
          </div>
          <div class="flex toolbox">
            <span class="mr-8">{{ form.messageList.length }}/100</span>
            <div v-for="(item, index) in typeList" :key="index" class="mr-8">
              <el-button
                size="small"
                class="btn_item"
                @click="handleTypeOpen(item)"
              >
                {{ item.name }}
                <input
                  v-if="item.id == 2 || item.id == 3 || item.id == 4"
                  type="file"
                  :id="'photo' + index"
                  class="filebtn"
                  :accept="item.accept"
                  @change="chooseUpload($event, item, index)"
                />
                <el-tooltip
                  class="item"
                  effect="dark"
                  popper-class="btntooltip"
                  :content="item.info"
                  placement="top-start"
                >
                  <i v-if="item.info" class="el-icon-info"></i>
                </el-tooltip>
              </el-button>
            </div>
          </div>
        </el-form-item>
      </div>
      <div class="flexend">
        <el-button
          type="primary"
          :loading="subloading"
          size="small"
          @click="handleSubmit"
          >{{ title == "复制话术" ? "复制并创建" : "提交并创建" }}</el-button
        >
        <el-button size="small" @click="handleClose">取消</el-button>
      </div>
    </el-form>
    <!-- 文本 -->
    <reply-text
      v-if="opentext"
      :visable="opentext"
      :title="replytitle"
      :selectItem="selectItem"
      :selectIndex="selectIndex"
      @submit="addSubmit"
      @close="handleReplyClose"
    />
    <!-- 链接 -->
    <reply-link
      v-if="openlink"
      :visable="openlink"
      :title="replytitle"
      :selectItem="selectItem"
      @submit="addSubmit"
      @close="handleReplyClose"
    />
    <!-- 素材库 -->
    <reply-material
      v-if="openmaterial"
      :visable="openmaterial"
      :type="opentype"
      title="从素材库导入"
      :selectItem="selectItem"
      @submit="addSubmit"
      @close="handleReplyClose"
    />
  </el-drawer>
</template>
<script>
import {
  scriptGroupList,
  addScriptItem,
  updateScriptItem,
} from "@/api/market/reply";
import ReplyText from "./ReplyText.vue";
import ReplyLink from "./ReplyLink.vue";
import ReplyMaterial from "./ReplyMaterial.vue";
import { isOverSize } from "@/utils/validate";
export default {
  components: { ReplyText, ReplyLink, ReplyMaterial },
  data() {
    return {
      options: [],
      propsCascader:{
        label: 'groupName',
        value: 'id',
        checkStrictly: true 
      },
      form: {
        id: undefined,
        itemOrderIndex: undefined,
        group: "",
        title: "",
        messageList: [],
      },
      rules: {
        group: [{ required: true, message: "请选择分组", trigger: "change" }],
        title: [{ required: true, message: "请输入话术标题", trigger: "blur" }],
        messageList: [
          { required: true, message: "请添加话术内容", trigger: "blur" },
        ],
      },
      typeList: [
        { id: 1, name: "文字", type: "text" },
        { id: 2, name: "图片", type: "img", accept: "image/*" },
        {
          id: 3,
          name: "视频",
          type: "video",
          accept: "video/*",
          info: "发送视频传送比较耗时，如果发送消息间隔设置又较短，可能会出现消息乱序，所以视频尽量压缩小一点",
        },
        { id: 4, name: "文件", type: "file", accept: "" },
        { id: 5, name: "链接", type: "link" },
        { id: 6, name: "小程序", type: "program" },
        { id: 7, name: "视频号", type: "videoplus" },
        { id: 8, name: "表情", type: "emjoy" },
        {
          id: 9,
          name: "素材库",
          type: "material",
          info: "素材库支持小程序、视频号的素材形式",
        },
      ],
      opentext: false,
      replytitle: "",
      selectItem: null,
      selectIndex: "",
      opentype: "",
      openlink: false,
      openmaterial: false,
      subloading: false,
      positionIndex:'',//位置
    };
  },
  props: {
    title: {
      type: String,
      default: "",
    },
    rowitem: {
      type: Object,
      default: null,
    },
  },
  async created() {
    await this.getScriptGroupList();
    if (this.rowitem) {
      this.form.id = this.rowitem.id;
      this.form.itemOrderIndex = this.rowitem.itemOrderIndex;
      this.form.title = this.rowitem.title;
      this.form.messageList = this.rowitem.contentList;
      // console.log('this.form.:',this.form)
    }
  },
  methods: {
    getScriptGroupList() {
      scriptGroupList({
        pageSize: 9999,
        pageNum: 1,
        repoType: 1,
      }).then((res) => {
        this.options = [
          { id: -2, groupName: "全部分组" },
          { id: -1, groupName: "默认分组" }
        ].concat(this.handleTree(res.rows, "id", "parentGroupId"));
        if(this.rowitem){
          this.form.group = this.getParentsById(this.options,this.rowitem.groupId)
          console.log('this.form.group:', this.form.group)
        }
      });
    },

    // 获取父级id
    getParentsById(list, id) {
      for (let i in list) {
        if (list[i][this.propsCascader.value || 'value'] == id) {
          return [list[i][this.propsCascader.value || 'value']]
        }
        if (list[i].children) {
          let node = this.getParentsById(list[i].children, id)
          if (node !== undefined) {
            // 追加父节点
            node.unshift(list[i][this.propsCascader.value || 'value'])
            return node
          }
        }
      }
    },

    handleChange(node) {
      console.log("node:", node);
    },

    handleTypeOpen(item,index) {
      if(this.form.messageList.length>=100){
        this.$message.warning('内容条数最大限制为100')
        return
      }
      this.opentype = item.id;
      if(index || index === 0){
        this.positionIndex = index
      }
      switch (item.id) {
        case 1:
          this.opentext = true;
          this.replytitle = "添加文字";
          break;
        case 5:
          this.openlink = true;
          this.replytitle = "添加链接";
          break;
        case 6:
        case 7:
        case 9:
          this.openmaterial = true;
          break;
        default:
          break;
      }
    },

    addSubmit(obj) {
      console.log("obj", obj, this.positionIndex);
      if (this.selectItem) {
        console.log('编辑的')
        //编辑的
        this.form.messageList[obj.index].contentJson = obj.message;
        // this.selectItem.message = obj;
      } else {
        console.log('添加的')
        //添加的
        switch (obj.type) {
          case 1: //文字
            let item = {
              contentType: "文本",
              contentJson: obj.message,
            }
            if(this.positionIndex||this.positionIndex===0){ //指定位置添加
              console.log('111111111')
              this.form.messageList.splice(this.positionIndex + 1, 0, item)
            }else{ //直接添加
              console.log('222222')
              this.form.messageList.push(item);
            }
            break;
          default:
            break;
        }
      }
      this.handleReplyClose(1);
    },

    handleReplyClose(type) {
      // 位置置空
      this.positionIndex = ''
      switch (type) {
        case 1:
          this.opentext = false;
          this.selectItem = null;
          break;
        case 5:
          this.openlink = false;
          this.selectItem = null;
          break;
        case 6:
        case 7:
        case 9:
          this.openmaterial = false;
          this.selectItem = null;
        default:
          break;
      }
    },

    chooseUpload(event, item, index) {
      var file = event.currentTarget.files[0];
      if (isOverSize(file.size, 5)) {
        this.$message.warning("大小不能超过5MB");
        return;
      }
      console.log(file);
      //   var formData = new FormData();
      //   formData.append("file", file);
      //   formData.append("uid",localStorage.getItem('uid'));
      //   post("upload/Img", formData).then((response) => {
      //     if (response.code == 1) {
      //       if (num == 1) {
      //         item.pageData.imgurl = response.data;
      //         document.getElementById("pageData" + index).value = null;
      //       } else {
      //         item.images = response.data;
      //         document.getElementById("photo"+ index).value = null;
      //       }
      //       this.$message({
      //         duration: 800,
      //         message: "上传成功",
      //         type: "success",
      //       });
      //     } else {
      //       this.$message.error(response.msg);
      //     }
      //   });
    },

    handleDelete(item, index) {
      this.form.messageList.splice(index, 1);
    },

    handleEdit(item, index) {
      if (item.contentType == "文本") {
        this.selectItem = item;
        this.selectIndex = index;
        this.opentext = true;
        this.replytitle = "编辑文字";
      }
    },
    // 下移
    handleMoveDown(index) {
      let arr = this.form.messageList;
      arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    },
    // 上移
    handleMoveTop(index) {
      let arr = this.form.messageList;
      arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    },

    // 置底
    handleDown(index) {
      let arr = this.form.messageList;
      arr.push(arr.splice(index, 1)[0]);
    },
    // 置顶
    handleTop(index) {
      let arr = this.form.messageList;
      arr.unshift(arr.splice(index, 1)[0]);
    },

    // 关闭弹窗
    handleClose(type = 0) {
      this.$emit("close", type); //关闭弹窗;
    },

    handleSubmit() {
      console.log('this.form.group:', this.form.group)
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        if (this.form.id && this.title == "编辑话术") {
          let params = {
            id: this.form.id,
            itemOrderIndex: this.form.itemOrderIndex,
            groupId: this.form.group[this.form.group.length - 1],
            title: this.form.title,
            contentList: this.form.messageList.map((item, index) => {
              item.contentOrderIndex = index + 1;
              return item;
            }),
          };
          // console.log('params:', params)
          this.subloading = true;
          updateScriptItem(params)
            .then((res) => {
              this.$message.success("修改成功");
              this.handleClose(1);
              this.subloading = false;
            })
            .catch(() => {
              this.subloading = false;
            });
        } else {
          let params = {
            groupId: this.form.group[this.form.group.length - 1],
            title: this.form.title,
            contentList: this.form.messageList.map((item, index) => {
              item.contentOrderIndex = index + 1;
              return item;
            }),
          };
          this.subloading = true;
          addScriptItem(params)
            .then((res) => {
              this.$message.success("添加成功");
              this.handleClose(1);
              this.subloading = false;
            })
            .catch(() => {
              this.subloading = false;
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.formcard {
  padding-top: 12px;
  margin-bottom: 12px;
  background: #fafafa;
  padding-right: 12px;
  border: 1px solid #f0f0f0;
}
.btn_item {
  padding: 0 7px;
  height: 26px !important;
  font-size: 14px !important;
  overflow: hidden;
  position: relative;

  .filebtn {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    opacity: 0;
  }
}
.numberindex {
  width: 20px;
  height: 20px;
  line-height: 20px;
  font-size: 12px;
  background: #ddd;
  border-radius: 50%;
  display: inline-block;
  text-align: center;
}
.m_textbox {
  max-width: 312px;
  word-break: break-all;
  padding: 8px 12px;
  font-size: 15px;
  color: #000;
  background: #fff;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
  line-height: normal;
}
.messbox {
  border: 1px solid #e9e9e9;
  border-bottom: none;
}
.messageitem {
  min-height: 60px;
  &:hover {
    background-color: #f5f5f5;
  }
}
.toolbox {
  min-height: 47px;
  padding: 8px 16px;
  background: #f7f7f7;
  border: 1px solid #e9e9e9;
}
.m_btn {
  height: 28px !important;
  width: 28px !important;
  border: 1px solid #e9e9e9;
  padding: 0 !important;
  line-height: 28px;
  border-radius: 4px;
}
.m_line {
  width: 1px;
  background: #e9e9e9;
  height: 20px;
  margin: 4px 16px 4px 8px;
}
.m_imgbox {
  max-width: 160px;
  max-height: 160px;
  border-radius: 5px;
}
.dropflex{
  padding: 6px 16px;
}
</style>